<template>
  <view class="register-container">
    <view class="register-form">
      <view class="logo-container">
        <image src="/static/logo.png" class="logo"></image>
        <view class="title">账号注册</view>
      </view>
      
      <view class="form-item">
        <view class="input-wrapper">
          <uni-icons type="person" size="20" color="#999" class="input-icon"></uni-icons>
          <input type="text" v-model="registerForm.username" placeholder="请输入用户名" class="input" />
        </view>
      </view>
      
      <view class="form-item">
        <view class="input-wrapper">
          <uni-icons type="mobile" size="20" color="#999" class="input-icon"></uni-icons>
          <input type="number" v-model="registerForm.phonenumber" placeholder="请输入手机号" class="input" />
        </view>
      </view>
      
      <view class="form-item">
        <view class="input-wrapper">
          <uni-icons type="locked" size="20" color="#999" class="input-icon"></uni-icons>
          <input type="password" v-model="registerForm.password" placeholder="请输入密码" class="input" />
        </view>
      </view>
      
      <view class="form-item">
        <view class="input-wrapper">
          <uni-icons type="locked" size="20" color="#999" class="input-icon"></uni-icons>
          <input type="password" v-model="registerForm.confirmPassword" placeholder="请再次输入密码" class="input" />
        </view>
      </view>
      
      <view class="form-item" v-if="captchaEnabled">
        <view class="input-wrapper">
          <uni-icons type="text" size="20" color="#999" class="input-icon"></uni-icons>
          <input type="text" v-model="registerForm.code" placeholder="请输入验证码" class="input" maxlength="4" />
          <!-- 验证码区域 - 显示验证码图片 -->
          <div class="login-code" @click="refreshCode">
            <image :src="codeUrl" class="login-code-img"></image>
          </div>
        </view>
      </view>
      
      <button class="register-btn" @click="handleRegister" :loading="loading">注册</button>
      
      <view class="login-link">
        <text>已有账号？</text>
        <text @click="goToLogin" class="link">返回登录</text>
      </view>
    </view>
  </view>
</template>

<script>
import { register, getCodeImg } from '@/api/user'

export default {
  data() {
    return {
      registerForm: {
        username: '',
        phonenumber: '',
        password: '',
        confirmPassword: '',
        code: '',
        uuid: '',
        userType: 'sys_user' // 用户类型，与RuoYi后端保持一致
      },
      loading: false,
      codeUrl: '',
      captchaEnabled: true // 验证码开关
    }
  },
  onLoad() {
    // 初始化时获取验证码
    this.refreshCode()
  },
  methods: {
    // 刷新验证码
    async refreshCode() {
      try {
        console.log('开始获取验证码...')
        const res = await getCodeImg()
        console.log('验证码接口返回:', res)
        
        if (res.code === 200 && res.data) {
          // 检查是否启用验证码
          this.captchaEnabled = res.data.captchaEnabled === undefined ? true : res.data.captchaEnabled
          if (this.captchaEnabled) {
            // 设置验证码图片URL
            this.codeUrl = `data:image/gif;base64,${res.data.img}`
            // 设置验证码UUID
            this.registerForm.uuid = res.data.uuid
          }
          console.log('验证码UUID:', this.registerForm.uuid)
        } else {
          console.error('验证码接口返回异常:', res)
          // 错误情况下使用时间戳作为UUID
          this.registerForm.uuid = Date.now().toString();
        }
      } catch (error) {
        console.error('获取验证码失败:', error)
        // 错误情况下使用时间戳作为UUID
        this.registerForm.uuid = Date.now().toString();
      }
    },
    
    // 表单验证
    validateForm() {
      // 用户名验证
      if (!this.registerForm.username.trim()) {
        uni.showToast({
          title: '请输入用户名',
          icon: 'none'
        })
        return false
      }
      
      if (this.registerForm.username.length < 4 || this.registerForm.username.length > 20) {
        uni.showToast({
          title: '用户名长度应在4-20个字符之间',
          icon: 'none'
        })
        return false
      }
      
      // 手机号验证（可选）
      if (this.registerForm.phonenumber.trim()) {
        const phoneRegex = /^1[3-9]\d{9}$/
        if (!phoneRegex.test(this.registerForm.phonenumber)) {
          uni.showToast({
            title: '请输入有效的手机号',
            icon: 'none'
          })
          return false
        }
      }
      
      // 密码验证
      if (!this.registerForm.password.trim()) {
        uni.showToast({
          title: '请输入密码',
          icon: 'none'
        })
        return false
      }
      
      if (this.registerForm.password.length < 6) {
        uni.showToast({
          title: '密码长度至少6位',
          icon: 'none'
        })
        return false
      }
      
      // 确认密码验证
      if (this.registerForm.password !== this.registerForm.confirmPassword) {
        uni.showToast({
          title: '两次输入的密码不一致',
          icon: 'none'
        })
        return false
      }
      
      // 验证码验证
      if (this.captchaEnabled && !this.registerForm.code.trim()) {
        uni.showToast({
          title: '请输入验证码',
          icon: 'none'
        })
        return false
      }
      
      return true
    },
    
    // 处理注册
      async handleRegister() {
        if (!this.validateForm()) {
          return
        }
        
        this.loading = true
        try {
          // 准备注册数据
          const registerData = {
            username: this.registerForm.username,
            phonenumber: this.registerForm.phonenumber || '',
            password: this.registerForm.password,
            code: this.registerForm.code,
            uuid: this.registerForm.uuid,
            userType: this.registerForm.userType
          }
          
          console.log('提交注册数据:', {
            username: registerData.username,
            phonenumber: registerData.phonenumber,
            password: '******', // 不打印密码
            code: registerData.code,
            uuid: registerData.uuid,
            userType: registerData.userType
          })
          
          // 调用注册接口 - 符合RuoYi框架要求
          const res = await register(registerData, { withToken: false, withEncrypt: true })
          
          console.log('注册接口返回:', res)
          
          if (res.code === 200) {
            uni.showToast({
              title: res.msg || '注册成功',
              icon: 'success'
            })
            
            // 延迟跳转到登录页面
            setTimeout(() => {
              this.goToLogin()
            }, 1500)
          } else {
            // 注册失败，显示错误信息
            uni.showToast({
              title: res.msg || '注册失败，请稍后重试',
              icon: 'none'
            })
            
            // 刷新验证码
            if (this.captchaEnabled) {
              this.refreshCode()
            }
          }
        } catch (error) {
          console.error('注册失败:', error)
          uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none'
          })
        } finally {
          this.loading = false
        }
      },
    
    // 跳转到登录页面
      goToLogin() {
        uni.navigateTo({
          url: '/pages/mine/login'
        })
      }
    }
  }
</script>

<style scoped>
.register-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 0 40rpx;
}

.register-form {
  width: 100%;
  max-width: 600rpx;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 60rpx 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.logo-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 60rpx;
}

.logo {
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 20rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.form-item {
  margin-bottom: 40rpx;
  width: 100%;
}

.input-wrapper {
  display: flex;
  align-items: center;
  position: relative;
  background-color: #fff;
  padding: 0 30rpx;
  height: 96rpx;
  border-bottom: 2rpx solid #eee;
}

.input-icon {
  margin-right: 20rpx;
  position: static;
}

.input {
  flex: 1;
  height: 100%;
  font-size: 32rpx;
  color: #333;
  padding-left: 0;
}

.input::placeholder {
  color: #999;
}

/* 验证码图片样式 */
.login-code {
  width: 200rpx;
  height: 60rpx;
  cursor: pointer;
  margin-left: 20rpx;
}

.login-code-img {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

/* 按钮样式 */
.register-btn {
  width: 100%;
  height: 88rpx;
  background-color: #007aff;
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
  margin-top: 20rpx;
  margin-bottom: 40rpx;
}

.register-btn:active {
  background-color: #0051d5;
}

/* 登录链接样式 */
.login-link {
  display: flex;
  justify-content: center;
  font-size: 28rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.link {
  color: #007aff;
  margin-left: 8rpx;
}
</style>